import Driver from './Driver'

const events = {}
let ready = false
const driver = new Driver('_distortion')
class DriverStorage {
    constructor () {
    }

    setItem(key, value){
        const self = this
        self[key] = value
        driver.update('storage', {key: key, value: value})
    }

    getItem(key) {
        return driver.table('storage').queryByKey(key).then(kv => kv && kv.value)
    }

    removeItem(key) {
        delete this[key]
        return driver.delete('storage', key)
    }

    ready(fn){
        if(ready) {
            fn.call(this, this)
            return
        }
        events.ready = fn
    }
}

const driverStorage = new DriverStorage();
driver.on('success', () => {
    driver.select('storage').then(arr => {
        arr.forEach(kv => driverStorage[kv.key] = kv.value)
        ready = true
        events.ready && events.ready.call(events, driverStorage)
    })
})

driver.open().then(() => {
    driver.createTable({
        name: 'storage',
        primaryKey: 'key',
        indexes: [
            {name: 'name_index', column: 'key', unique: true},
        ],
    })
})

export default driverStorage
